# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

from conan import ConanFile
from conan.tools.env import VirtualBuildEnv
from conan.tools.gnu import Autotools, AutotoolsToolchain
from conan.tools.files import get, copy
from conan.tools.layout import basic_layout
import os

required_conan_version = ">=2.13.0"


class BisonConan(ConanFile):
    name = "bison"
    license = "GPL-3.0-or-later"
    description = "Bison is a general-purpose parser generator"
    settings = "os", "compiler", "build_type", "arch"
    package_type = "application"
    
    def layout(self):
        basic_layout(self)

    def source(self):
        get(self, **self.conan_data["sources"][self.version],
            strip_root=True)
    
    def generate(self):
        tc = AutotoolsToolchain(self)
        chost = self.buildenv.vars(self).get("CHOST")
        if chost:
            self.output.info(f"Setting CROSS_COMPILE={chost}-")
            tc.make_args.append(f"CROSS_COMPILE={chost}-")
        tc.configure_args.extend(["--datarootdir=${prefix}/share"])
        tc.generate()

    def build(self):
        autotools = Autotools(self)
        autotools.configure()
        autotools.make()

    def package(self):
        autotools = Autotools(self)
        autotools.install()
        
        # 复制必要的许可证文件
        copy(self, "COPYING", 
             src=self.source_folder, 
             dst=os.path.join(self.package_folder, "licenses"))

    def package_info(self):
        # 将二进制路径添加到环境变量
        self.cpp_info.bindirs = ["bin"]
        self.buildenv_info.define_path("BISON_PKGDATADIR", os.path.join(self.package_folder, "share", "bison"))
        self.buildenv_info.define_path("CONAN_BISON_ROOT", self.package_folder)